class AsyncPool {
    constructor(maxConcurrent) {
        if (!Number.isInteger(maxConcurrent) || maxConcurrent <= 0) {
            throw new Error('maxConcurrent 必须是大于 0 的整数');
        }
        this.maxConcurrent = maxConcurrent;
        this.running = 0;
        this.queue = [];
        this.results = []; // 收集所有任务结果（成功/失败）
    }

    /**
     * 添加任务
     * @param {() => Promise<any>} task
     * @param {string|number} id 可选的任务标识，用于结果追踪
     */
    add(task, id = this.results.length) {
        return new Promise((resolve, reject) => {
            const wrapped = { task, resolve, reject, id };
            this.queue.push(wrapped);
            this._tryRun();
        });
    }

    _tryRun() {
        if (this.running >= this.maxConcurrent || this.queue.length === 0) return;

        const { task, resolve, reject, id } = this.queue.shift();
        this.running++;

        Promise.resolve(task())
            .then(value => {
                const result = { status: 'fulfilled', value, id };
                this.results[id] = result;
                resolve(result);
            })
            .catch(reason => {
                const result = { status: 'rejected', reason, id };
                this.results[id] = result;
                // reject(result);
                this.queue.length = 0;
            })
            .finally(() => {
                this.running--;
                this._tryRun();
            });
    }

    // 等待所有任务完成（包括队列中的）
    waitAll() {
        return new Promise(resolve => {
            const check = () => {
                if (this.running === 0 && this.queue.length === 0) {
                    resolve(this.results);
                } else {
                    setImmediate(check);
                }
            };
            check();
        });
    }

    // 获取当前已完成的结果（可随时调用）
    getResults() {
        return [...this.results];
    }
}


// 模拟异步任务（有成功、有失败）
function mockTask(id) {
    return async () => {
        const delay = Math.random() * 800 + 300;
        console.log(`Task ${id} 开始，预计 ${delay.toFixed(0)}ms`);
        await new Promise(r => setTimeout(r, delay));

        if (id % 4 === 0) {
            throw new Error(`Task ${id} 故意失败`);
        }
        return `Success: ${id} - ${new Date().toISOString()}`;
    };
}

(async () => {
    const pool = new AsyncPool(3); // 最多3个并发

    const promises = [];
    for (let i = 1; i <= 10; i++) {
        const taskFn = mockTask(i);
        promises.push(
            pool.add(taskFn, i) // id 传 i，方便追踪
                .then(res => console.log('Success:', res.value))
                .catch(err => console.error('Failed:', err.reason.message))
        );
    }

    // 方式1：等待所有任务完成，获取完整结果
    const allResults = await pool.waitAll();

    console.log('\n=== 所有任务最终结果 ===');
    allResults.forEach((res, idx) => {
        if (res.status === 'fulfilled') {
            console.log(`Success [${idx}]:`, res.value);
        } else {
            console.log(`Failed [${idx}]:`, res.reason.message || res.reason);
        }
    });

    // 方式2：实时获取已完成结果（不等待）
    // setInterval(() => {
    //   console.log('当前已完成:', pool.getResults().filter(r => r));
    // }, 500);
})();